/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.api.utils;

import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import javax.servlet.http.Cookie;

/**
 * 验证Session是否有效
 */
@Slf4j
public class Validator {

    /**
     * 验证会话是否有效
     *
     * @param cks
     * @param serviceId
     */
    public static void CheckCksSession(Cookie[] cks, String serviceId) {
        var cookieName = CafEnvironment.getEnvironment().getProperty("caf-security.general.cookie-name") == null ?
                "caf_web_session" : CafEnvironment.getEnvironment().getProperty("caf-security.general.cookie-name");

        var isLog = false;
        var logMsg = "current rpc service:" + serviceId + "invoking";
        if (cks == null || cks.length == 0) {
            logMsg = logMsg + "，current cookies is null or empty,has 401 risk";
            isLog = true;
        } else {
            var isHasSession = false;
            var sessionValue = "";
            for (var c : cks) {
                if (c.getName().equals(cookieName)) {
                    isHasSession = true;
                    sessionValue = c.getValue();
                    break;
                }
            }

            if (isHasSession && org.springframework.util.StringUtils.isEmpty(sessionValue)) {
                logMsg = logMsg + "，current" + cookieName + "is null，has 401 risk";
                isLog = true;
            }

            if (!isHasSession) {
                logMsg = logMsg + ",current cookies has no " + cookieName + ",has 401 risk";
                isLog = true;
            }
        }

        if (isLog) {
            log.warn("rpc service cookies exception：" + cookieName + ":" + logMsg);
        }
    }
}
